package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.properties.MinioProperties;
import com.atguigu.spzx.manager.service.FileUpdateService;
import io.minio.*;
import org.apache.commons.compress.utils.FileNameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileUpdateServiceImpl implements FileUpdateService {
    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String fileUpload(MultipartFile multipartFile) {

        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();

            // 查看桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .build());

            if(!found){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .config(createBucketPolicyConfig(minioProperties.getBucketName()))
                        .build());
            }

            String date = new SimpleDateFormat("yyyyMMdd")
                    .format(new Date());
            String extFileName = FileNameUtils.getExtension(multipartFile.getOriginalFilename());
            String uuid = UUID.randomUUID().toString().replace("-","");
            String fileName = date + "/" + uuid + "." + extFileName;

            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName()).stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .object(fileName).build());

            return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName;

        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    private String createBucketPolicyConfig(String bucketName) {
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}
